import type { ConfigEnv } from 'vite'
import process from 'node:process'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import { getPluginsList } from './build/plugins'
import { convertEnv } from './build/utils'

export default defineConfig(async (configEnv: ConfigEnv) => {
  const viteEnv = convertEnv(loadEnv(configEnv.mode, process.cwd()))
  const { VITE_PUBLIC_PATH, VITE_PORT, VITE_USE_MOCK } = viteEnv
  return {
    base: VITE_PUBLIC_PATH,
    server: {
      host: '0.0.0.0',
      port: VITE_PORT,
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ['./index.html', './src/{pages,components}/*'],
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    plugins: await getPluginsList(VITE_USE_MOCK),
    build: {
      target: 'es6',
      cssTarget: 'chrome61',
      reportCompressedSize: false,
      sourcemap: false,
      chunkSizeWarningLimit: 1024, // chunk 大小警告的限制（单位kb）
      commonjsOptions: {
        ignoreTryCatch: false,
      },
    },
    optimizeDeps: {
      exclude: ['vue-demi'],
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/config/theme.scss";',
        },
      },
    },
  }
})
